package com.geovoice;

//import java.util.ArrayList;
import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.content.Context;
//import android.app.Activity;
//import android.content.Context;
//import android.content.ComponentName;
//import android.content.Context;
//import android.content.Intent;
//import android.content.ServiceConnection;
//import android.content.pm.ActivityInfo;
//import android.database.Cursor;
//import android.database.sqlite.SQLiteDatabase;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
//import android.location.Location;
////import android.location.LocationListener;
//import android.location.LocationManager;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
//import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
//import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
//import android.widget.RelativeLayout;
//import android.widget.ZoomControls;

//import com.google.android.maps.GeoPoint;
//import com.google.android.maps.MapActivity;
//import com.google.android.maps.MapController;
//import com.google.android.maps.MapView;
//import com.google.android.maps.MyLocationOverlay;
//import com.google.android.maps.OverlayItem;
//import com.google.android.maps.MyLocationOverlay;
//import com.google.android.maps.Overlay;

import org.osmdroid.util.GeoPoint;
//import org.osmdroid.views.MapController;
//import org.osmdroid.views.MapView;
//import org.osmdroid.views.overlay.MyLocationOverlay;
//import org.osmdroid.views.overlay.Overlay;
//import org.osmdroid.views.overlay.OverlayItem;



//import com.rdc.R;

//import com.google.android.maps.OverlayItem;

/*    This file is part of Geovoice.

Geovoice is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Geovoice is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Geovoice.  If not, see <http://www.gnu.org/licenses/>.  */

public class LocationMap extends Activity {

	String TAG = "GEOVOICE - LocationMap";
	private LocationManager locationManager;

//	Button myLocationButton;
	Button setButton;
	Button cancelButton;
    Button homeButton; 
	Location location;
	int latitude;
	int longitude;
	String locationName;
	boolean isNewLocation = false;
	int radius = 100;
	WebView webView;
	ProgressBar myProgressBar;
	int myProgress = 0;
	int test = 0;
	private static final String MAP_URL = "file:///android_asset/map.html";
//	private static final String MAP_URL = "http://www3.ns.sympatico.ca/brkeith/map.htm";
	
//	List<Overlay> mapOverlays;
	Drawable drawable;
//	HelloItemizedOverlay itemizedOverlay;
//	MyLocationOverlay myLocation;
//	 GeoPoint point = new GeoPoint(37421791,-122084006);
     GeoPoint point = new GeoPoint(0, 0);

//	GeoPoint centrepoint = new GeoPoint(39421791, -98084006);
//	private MapController mapController;
//	protected MapView mapView;
 // private LocationManager locationManager;

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);

		// setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
		this.getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);	
		setContentView(R.layout.currentlocation); // bind the layout to the
													// activity
		setTitle("Select Location");
//		myLocationButton = (Button) findViewById(R.id.thisLocation);
		setButton = (Button) findViewById(R.id.mapSetButton);
		cancelButton = (Button) findViewById(R.id.mapCancelButton);
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		setButton.setBackgroundResource(R.drawable.button);
		cancelButton.setBackgroundResource(R.drawable.button);
//		myLocation = new MyLocationOverlay(this, mapView);
//		myLocation.enableMyLocation();
//		myLocation.enableCompass();
	
	
		if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		}
		else if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
			location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		}

		Bundle receivedBundle = getIntent().getExtras();

		locationName = receivedBundle
				.getString(Settings.LOCATION_NAME_EXTRA/* "locationName" */);

		try {
			radius = receivedBundle.getInt(Settings.RADIUS_EXTRA/* "radius" */);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (receivedBundle.containsKey("isNew"))
				isNewLocation = receivedBundle.getBoolean("isNew");
		} catch (Exception r) {
			r.printStackTrace();
		}

//		mapController = mapView.getController();
//		mapController.setCenter(centrepoint);
//		mapController.setZoom(4);
		try {
			latitude = receivedBundle
					.getInt(Settings.LATITUDE_EXTRA/* "latitude" */);
			longitude = receivedBundle
					.getInt(Settings.LONGITUDE_EXTRA/* "longitude" */);
			if (latitude == 0 || longitude == 0) {
     		    latitude = (int)(location.getLatitude()* 1E6); 
     		    longitude = (int)(location.getLongitude()* 1E6);
//				point = new GeoPoint(lat, lon);
				Log.e("GEOVOICE", "LAT LON SET " + latitude + " " + longitude);
//				mapController.setCenter(point);
//				mapController.setZoom(6);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}


		setButton.setOnClickListener(setClick);
		cancelButton.setOnClickListener(cancelClick);

		try {
	//		myLocationButton.bringToFront();
	//		myLocationButton.setClickable(true);

//			try {
 //    		    latitude = (int)Math.round(location.getLatitude()* 1E6); 
 //    		    longitude = (int)Math.round(location.getLongitude()* 1E6);

//				myLocation.setLatitude(latitude);
//				myLocation.setLongitude(longitude);


//			GeoPoint gpp = myLocation.getMyLocation();

//				if (gpp != null) {
//					point = gpp;
//					mapController.setCenter(point);
//				}
//			} catch (Exception t) {
//				Log.e("FAIL", "Exception Occured " + t.getLocalizedMessage()
//						+ t.getStackTrace()[0] + t.getStackTrace()[1]);
//			}
//			webView = (WebView) findViewById(R.id.webView1);
//			webView.getSettings().setJavaScriptEnabled(true);
//			webView.loadUrl("http://maps.google.com/maps?q="+ latitude/1E6 +","+ longitude/1E6 + "(Current Location)&iwloc=A&hl=en");
		

			// myLocation.enableCompass();

			Log.i("GEOVOICE", "Before Map Overlay");
//			mapOverlays = mapView.getOverlays();
//			drawable = this.getResources().getDrawable(
//					R.drawable.mapmarkergreen);
			Log.i("GEOVOICE", "Resource Definition");
//			itemizedOverlay = new HelloItemizedOverlay(drawable, this);
			Log.i("GEOVOICE", "Done with BasisOverlay Creation");

//			 OverlayItem overlayitem = new OverlayItem(point, "myLocation",
//			 "myLocation");

			// BasisOverlay bo = new BasisOverlay(itemizedOverlay);
			Log.i("GEOVOICE", "Done with OverlayItem");
//			 itemizedOverlay.addOverlay(overlayitem);

			// Overlay g = new Overlay();
			// mapOverlays.add(bo);
//			mapOverlays.add(itemizedOverlay);
			// mapOverlays.
//			mapOverlays.add(myLocation);
			Log.i("GEOVOICE", "Done adding Overlay");

	//		myLocationButton.setOnClickListener(new OnClickListener() {
	//			@Override
	//			public void onClick(View arg0) {
	//				try {
//						WebView webView = (WebView) findViewById(R.id.webView1);
//						webView = (WebView) findViewById(R.id.webView1);
//						webView.getSettings().setJavaScriptEnabled(true);
//						webView.loadUrl("http://maps.google.com/maps?q="+ latitude/1E6 +","+ longitude/1E6 + "(Current Location)&iwloc=A&hl=en");

//						GeoPoint p = myLocation.getMyLocation();
//						if (p != null) {
//							itemizedOverlay.onTap(p, mapView);
//							mapController.setCenter(p);
//							if (mapView.getZoomLevel() < 6) {
//								mapController.setZoom(6);
//							}
//						}
//					} catch (Exception e) {
//						System.out.println("Exception caught with Button");
//					}
//				}
//			});
			
	
	
		} catch (Exception e) {
			Log.e("FAIL",
					"Exception Occured " + e.getLocalizedMessage()
							+ e.getStackTrace()[0] + e.getStackTrace()[1]);
		}
		displayPage();
//		if (test == 0 ){
//		displayPage();
//		}
		
    homeButton = (Button) findViewById(R.id.homeButton); 
    homeButton.setBackgroundResource(R.drawable.button);
    homeButton.setOnClickListener(new OnClickListener() {  
        @Override  
        public void onClick(View v) {  
            Intent intent = new Intent(LocationMap.this, MainMenu.class);  
                    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);  
                    startActivity(intent);  
        }  
    });  
  
	}

		
private void displayPage(){
		
		webView = (WebView) findViewById(R.id.webView1);
/*		webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)   
            {
             //Make the bar disappear after URL is loaded, and changes string to Loading...
            setTitle("Loading...");
            setProgress(progress * 100); //Make the bar disappear after URL is loaded

             // Return the app name after finish loading
                if(progress == 100)
                	setTitle(R.string.app_name);
              }
            });  */
		webView.setVisibility(View.GONE);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.addJavascriptInterface(new IJavascriptHandler(), "cpjs");
		webView.setWebChromeClient(new HelloWebChromeClient());
//		webView.setWebViewClient(new HelloWebViewClient());
		webView.loadUrl(MAP_URL);
		webView.setVisibility(View.VISIBLE);
//		String Send_URL =  "javascript:displaymap(" + latitude/1E6 + "," + longitude/1E6 + ")";
//		webView.loadUrl(Send_URL);
//		Send_URL = "javascript:var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP}";
//		webView.loadUrl(Send_URL);
//		Send_URL = "javascript:map = new google.maps.Map(document.getElementById(\"map_canvas\"), myOptions)";
//		webView.loadUrl(Send_URL);
		
		
}
	
	
/*	
		private class HelloWebViewClient extends WebViewClient  
		{
		    @Override
		    public void onPageStarted(WebView view, String url, Bitmap favicon) {
		        // TODO Auto-generated method stub
		        super.onPageStarted(view, url, favicon);        
		        view.setVisibility(View.GONE);
//		        pbr.setVisibility(View.VISIBLE);

		    }       

		    @Override
		    public boolean shouldOverrideUrlLoading(WebView view, String url)
		    {           
		    view.loadUrl(url);  
		    return true;            
		    }

		    @Override
		    public void onPageFinished(WebView view, String url) {
		        // TODO Auto-generated method stub
		    	super.onPageFinished(view, url);            
		        view.setVisibility(View.VISIBLE);
//		        pbr.setVisibility(View.GONE);
//		        view.requestFocus();
//		    String centerURL = "javascript:centerAt(" + latitude/1E6  + "," + 
//		    			longitude/1E6 + ")";
//	        webView.loadUrl(centerURL);
//	    	centerURL = "javascript:centerOld(" + latitude/1E6  + "," + 
//	    			longitude/1E6 + ")";
	//    	webView.loadUrl(centerURL);
		    }
		}
		    */
		
		public class HelloWebChromeClient extends WebChromeClient
		{
		 
		    // Other methods implemented as needed
		 
		    @Override
		    public boolean onConsoleMessage(ConsoleMessage message)
		    {
		   Callback callback = new mCallback();
		    	if ( message == null )
		        {
		            return super.onConsoleMessage( message );
		        }
		 
		        String messageString = message.message();
		 
		        if ( messageString != null )
		        {
		            if ( messageString.contains( "Uncaught TypeError" ) )
		            {
		                if (callback != null )
		                {
		                    callback.blackBerry10Error();
		                    Log.d("***ERROR***", "Blackberry 10 error detected");
		                }
		            }
		        }  
		        Log.d("ShowMote", message.message() + " -- From line "
                        + message.lineNumber() + " of "
                        + message.sourceId() );
		        return true;
		    }
		    
		}
		
		

	
		
		

		
//		myLocation.runOnFirstFix(new Runnable(){

//			public void run() {
//				try{
//				if(point.getLatitudeE6()==37421791 && point.getLongitudeE6()==-122084006){
//					mapController.animateTo(myLocation.getMyLocation());
//					itemizedOverlay.onTap(myLocation.getMyLocation(), mapView);
//					mapController.setZoom(9);
//				}
//			catch(Exception d){
//					d.printStackTrace();
//				}
//			}});

	OnClickListener setClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
		if(latitude!=0 && longitude!=0){
			Intent setPrefIntent = new Intent(LocationMap.this,PhonePreference.class);
//				WebView webView = (WebView) findViewById(R.id.webView1);
//				webView.getSettings().setJavaScriptEnabled(true);
//				webView.loadUrl("http://maps.google.com/maps?q="+ latitude/1E6 +","+ longitude/1E6 + "(Current Location)&iwloc=A&hl=en");
				setPrefIntent.putExtra(Settings.LOCATION_NAME_EXTRA,locationName);
				setPrefIntent.putExtra(Settings.LATITUDE_EXTRA, latitude);
				setPrefIntent.putExtra(Settings.LONGITUDE_EXTRA, longitude);
				setPrefIntent.putExtra(Settings.RADIUS_EXTRA, radius);
				setPrefIntent.putExtra("isNew", isNewLocation);
				startActivity(setPrefIntent);
				LocationMap.this.finish();
		}
				else
				{
					Toast toast = Toast.makeText(LocationMap.this, "Invalid Location", Toast.LENGTH_SHORT);
					toast.show();
				}
		}

};

	OnClickListener cancelClick = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			Log.e("GEOVOICE", "CANCEL CLICK");
//			myLocation.disableCompass();
//			myLocation.disableMyLocation();
			finish();
		}
	};

	@Override
	protected void onPause() {
		super.onPause();
//		myLocation.disableMyLocation();
//		myLocation.disableCompass();
		this.finish();
	}


	protected boolean isRouteDisplayed() {
		return false;
	}

	void fireErrorToast() {
		Toast.makeText(
				this,
				"Error in Geopoint\n\rReselect Point.\n\rContact Developer if Error Persists",
				Toast.LENGTH_LONG);
	}

	@Override
	public void onResume() {
		super.onResume();
//		myLocation.enableMyLocation();
//		myLocation.enableCompass();
	}
	
	  final class IJavascriptHandler {
		   IJavascriptHandler() {
		   }

		   // This annotation is required in Jelly Bean and later:
		   @JavascriptInterface
		   public void sendToAndroid(String lat, String lng) {
		      // this is called from JS with passed value
			   latitude = (int) (Double.parseDouble(lat)*1E6);
			   longitude = (int) (Double.parseDouble(lng)*1E6);
		      Toast t = Toast.makeText(getApplicationContext(), latitude/1E6 + " " + longitude/1E6, Toast.LENGTH_SHORT);
		      t.show();

		   }
		   @JavascriptInterface
		   public void sendTest(String strTest) {
			      // this is called from JS with passed value
			   	  test =   Integer.valueOf(strTest);
			      Toast t = Toast.makeText(getApplicationContext(), test, Toast.LENGTH_SHORT);
			      t.show();
		}
		   
		   @JavascriptInterface
		   public double getLat() {
			      // this is called from JS with passed value
	 		    return latitude/1E6; 
		      
		}
		   @JavascriptInterface
		   public double getLng() {
		      // this is called from JS with passed value
				return longitude/1E6; 
	}
	  
}

	  
public interface Callback
	    {
	    	public void blackBerry10Error();
	    }
	    
public class mCallback implements Callback {

		@Override
		public void blackBerry10Error()
		{
		    if ( webView != null )
		    {
		        webView.reload();
		    }
		}
}


}








/*
 * try{
 * 
 * locationManager = (LocationManager)
 * getSystemService(Context.LOCATION_SERVICE);
 * 
 * Location l
 * =locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); int lat
 * = (int) (l.getLatitude() * 1E6); int lng = (int) (l.getLongitude() * 1E6);
 * System.out.println(lat+" "+lng); GeoPoint point = new GeoPoint(lat, lng);
 * mapController.setCenter(point); }catch(Exception r){ Log.e("Joe",
 * "Location exception"+r.getLocalizedMessage()); }
 */
/*
 * locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000,
 * 0, new GeoUpdateHandler());
 */

/*
 * private void locClick(){ Intent i = new Intent(LocationMap.this,
 * LocationsMenu.class);
 * 
 * Log.w("GEOVOICE", "Starting Activity"); LocationMap.this.startActivity(i);
 * }
 */

// @Override
// public void onPause(){
// try{
// unbindService(mConnection);
// }catch(Exception e){
// e.printStackTrace();
// }
// super.onPause();
// }
//
// @Override
// public void onDestroy(){
// try{
// unbindService(mConnection);
// }catch(Exception e){
// e.printStackTrace();
// }
// super.onDestroy();
// }

/*
 * private String[] getStringArSQLVertical(String query, SQLiteDatabase sql){
 * String[] ret = new String[0]; try{ Cursor c = sql.rawQuery(query, null);
 * List<String> list = new ArrayList<String>(); if(c!=null){
 * while(c.moveToNext()){ list.add(c.getString(0));
 * Log.e("GEOVOICE","GET STRING AR"+c.getString(0)); //c.moveToNext(); } }
 * 
 * 
 * if(list.size()>0){ ret = list.toArray(new String[list.size()]);
 * Log.e("GEOVOICE","GET STRING AR List size"+list.size()); //ret = new
 * String[list.size()]; //for(int i=0;i<list.size();i++){ // ret[i] =
 * list.get(i); //} } //c.getString(0); c.close(); }catch(Exception o){
 * 
 * o.printStackTrace(); } return ret; }
 */

/*
 * OnClickListener setClick = new OnClickListener(){
 * 
 * @Override public void onClick(View arg0) {
 * Log.e("GEOVOICE","Starting SET CLICK FINISH MAP"); //SQL SQLiteDatabase sql
 * = openOrCreateDatabase("db",0,null); try{ if(isNewLocation){
 * 
 * // String sqlString =
 * "INSERT INTO LOCATIONS (locationName, locationLatitude, locationLongitude, locationRadius, enabled) VALUES "
 * + //
 * "('"+locationName+"',"+point.getLatitudeE6()+","+point.getLongitudeE6()+","
 * +radius+",'"+true+"');"; // System.out.println(sqlString); // //
 * sql.execSQL(sqlString); // // // // sqlString =
 * "SELECT phoneName FROM PHONE;"; // //
 * System.out.println("SELECT phoneName from PHONE"); //
 * 
 * 
 * // String[] phones =getStringArSQLVertical(sqlString,sql); //
 * if(phones.length>0){ //
 * Log.e("TECHVENTUSPHONE","PHONES LENGTH "+phones.length); // for(int
 * i=0;i<phones.length;i++){ // System.out.println(
 * "INSERT INTO LOCATIONPHONEENABLE (locationName,phoneName,phoneEnable) VALUES ('"
 * +locationName+"','"+phones[i]+"',-"+2+");"); // sql.execSQL(
 * "INSERT INTO LOCATIONPHONEENABLE (locationName,phoneName,phoneEnable) VALUES ('"
 * +locationName+"','"+phones[i]+"',-"+2+");"); // // } // } //
 * sql.execSQL("INSERT INTO COMMAND (command) VALUES ('rectify');"); // }else{
 * 
 * // // String sqlString =
 * "UPDATE LOCATIONS SET locationLatitude = "+point.getLatitudeE6
 * ()+" , locationLongitude = "
 * +point.getLongitudeE6()+" where locationName = '"+locationName+"';"; //
 * System.out.println(sqlString); // sql.execSQL(sqlString); } sql.close();
 * }catch(Exception y){ Log.e("GEOVOICE","Exception thrown");
 * y.printStackTrace(); }
 * 
 * 
 * // locationName VARCHAR, locationLatitude DOUBLE," // + " locationLongitude
 * DOUBLE, locationRadius INTEGER
 * 
 * 
 * if(isNewLocation){
 * 
 * if(point==null){ fireErrorToast(); }else{ Intent i = new
 * Intent(LocationMap.this,LocationDecisionMenu.class);
 * 
 * i.putExtra("locationName",locationName); i.putExtra("locationLatitude",
 * point.getLatitudeE6()); i.putExtra("locationLongitude",
 * point.getLongitudeE6()); i.putExtra("locationRadius", radius);
 * i.putExtra("locationEnabled", true); startActivity(i); } }
 * 
 * Log.e("GEOVOICE","ABOUT TO FINISH MAP"); myLocation.disableCompass();
 * myLocation.disableMyLocation(); LocationMap.this.finish(); }
 * 
 * };
 */


// GVLServiceInterface mIRemoteService;
// private ServiceConnection mConnection = new ServiceConnection() {
// // Called when the connection with the service is established
// public void onServiceConnected(ComponentName className, IBinder service)
// {
// // Following the example above for an AIDL interface,
// // this gets an instance of the IRemoteInterface, which we can use to
// call on the service
// mIRemoteService = GVLServiceInterface.Stub.asInterface(service);
// }
//
// // Called when the connection with the service disconnects unexpectedly
// public void onServiceDisconnected(ComponentName className) {
// Log.e(TAG, "Service has unexpectedly disconnected");
// mIRemoteService = null;
// }
// };


